<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller
{
   function __construct()
    {
	parent::__construct();
	
	
	
	/*if (isset($_REQUEST['signed_request'])) {
	    $encoded_sig = null;
	    $payload = null;
	    list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
	    $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
	}
	
	if (!empty($data->app_data)) {
	    $get_data = explode(',', $data->app_data);
	    
	    switch($get_data[0]){
		case 2 :
		    $this->get_ticket();
		    exit;
		    break;
		case 3 :
		    $this->how_to_vote();
		    exit;
		    break;
		case 4 :
		    $this->table_show(FALSE);
		    exit;
		    break;
		case 5 :
		    if(isset($get_data[1])){
			$this->get_36(FALSE,$get_data[1]);
		    }else{
			$this->get_36(FALSE);
		    }
		    exit;
		    break;
		case 6 :
		    $this->award(FALSE);
		    exit;
		    break;
		case 7 :
		    $this->how_to_vote(FALSE);
		    exit;
		    break;
		case 8 :
		    $this->table_show(TRUE);
		    exit;
		    break;
		case 9 :
		    if(isset($get_data[1])){
			$this->get_36(FALSE,$get_data[1]);
		    }else{
			$this->get_36(FALSE);
		    }
		    exit;
		    break;
		case 10 :
		    $this->award(FALSE);
		    exit;
		    break;
		case 11 :
		    $this->award_announcement(TRUE);
		    exit;
		    break;
	    }
	}*/
    }
    
    function index()
    {
	$this->set_facebook_data();
	
	$data['is_like'] = $this->session->userdata('is_like');
	$data['fb_app_id'] = $this->session->userdata('fb_app_id');
	
	$this->mytpl->set_template('home/home.html');
	$this->mytpl->set_cache(86400);
	$this->mytpl->set_var($data);
	$this->mytpl->display();
    }
    
    private function set_facebook_data()
    {
	$this->load->library('myfacebook');
	$this->is_like = $this->myfacebook->is_liked();
	$facebook_porfile = $this->myfacebook->get_facebook_profile();
	$this->seve_facebook_user($facebook_porfile);
	$fb_id = $this->myfacebook->getUser();
	
	$this->load->model('admin/user_model','user_model');
	$user_info = $this->user_model->get_data(array('fbid'=>$fb_id));
	$user_id = $user_info['uid'];
	
	$newsessiondata = array(
	    'fb_app_id'  => $this->myfacebook->get_facebook_config('fb_app_id'),
	    'fb_page_url'  => $this->myfacebook->get_facebook_config('fb_page_url'),
	    'fb_id'  => $fb_id,
	    'is_like'     => $this->is_like,
	    'user_id' => $user_info['uid']
	);
	$this->session->set_userdata($newsessiondata);
	
    }
    
    private function seve_facebook_user($facebook_porfile)
    {
	$this->load->model('admin/user_model','user_model');
	if( ! $this->user_model->get_data(array('fbid' => $facebook_porfile['id'])))
	{
	    $data = array(
			    'fbid' => $facebook_porfile['id'],
			    'f_name' => $facebook_porfile['first_name'],
			    'l_name' => $facebook_porfile['last_name'],
			    'email' => $facebook_porfile['email'],
			    'timer' => time(),
			    'name' => $facebook_porfile['name'],
			    'gender' => $facebook_porfile['gender'],
			    'facebook_link' => $facebook_porfile['link'],
			  );
	    $this->user_model->insert_data($data);
	}
    }
    
    function form()
    {
	if($this->session->userdata('fb_app_id',TRUE) OR $this->session->userdata('fb_app_id') == '' ){
	    $this->set_facebook_data();
	}
	
	$data['fb_app_id'] = $this->session->userdata('fb_app_id');
	
	$this->mytpl->set_template('home/form-v2.html');
	$this->mytpl->set_cache(86400);
	$this->mytpl->set_var($data);
	$this->mytpl->display();
    }
    
    function form_check()
    {
	$data['status'] = TRUE;
	$data['error'] = '';
	
	//$name = strtoupper(trim($this->input->post('name')));
	//if($name != ''){
	//    $pattern = '/^[A-Z ]*$/';
	//    if( ! preg_match($pattern, $name)) {
	//	$data['status'] = FALSE;
	//	$data['error'] .= 'ชื่อต้องเป็นภาษาอังกฤษเท่านั้นค่ะ<br />';
	//    }else{
	//	$data['name'] = $name;
	//    }
	//}else{
	//    $data['status'] = FALSE;
	//    $data['error'] .= 'กรุณากรอกชื่อ-นามสกุลค่ะ<br />';
	//}
	
	$credit_6 = trim($this->input->post('credit-f')).trim($this->input->post('credit-s'));
	$credit_l = trim($this->input->post('credit-t'));
	if($credit_6 != '' OR $credit_l != ''){
	    $credit_no = array('477376', '496615', '490734', '454852', '490733', '540492', '541029', '541496');
	    if(in_array($credit_6, $credit_no)){
		$pattern = '/^[0-9]*$/';
		if( ! preg_match($pattern, $credit_l) OR $credit_l == '') {
		    $data['status'] = FALSE;
		    $data['error'] .= 'หมายเลขบัตรเครดิตไม่ถูกต้องค่ะ<br />';
		}else{
		    $data['credit'] = $credit_6.'xxxxxx'.$credit_l;
		}
	    }else{
		$data['status'] = FALSE;
		$data['error'] .= 'หมายเลขบัตรเครดิตไม่ถูกต้องค่ะ<br />';
	    }
	}else{
	    $data['status'] = FALSE;
	    $data['error'] .= 'กรุณากรอกหมายเลขบัตรเครดิตค่ะ<br />';
	}
	
	$personal_id = trim($this->input->post('id-f')).trim($this->input->post('id-s')).trim($this->input->post('id-t')).trim($this->input->post('id-4')).trim($this->input->post('id-5'));
	if($personal_id != ''){
	    $pattern = '/^[1-9][0-9]{12}$/';
	    if( ! preg_match($pattern, $personal_id)) {
		$data['status'] = FALSE;
		$data['error'] .= 'หมายเลขบัตรประชาชนไม่ถูกต้องค่ะ<br />';
	    }else{
		$data['name'] = $personal_id;
	    }
	}else{
	    $data['status'] = FALSE;
	    $data['error'] .= 'กรุณากรอกหมายเลขบัตรประชาชนค่ะ<br />';
	}
	
	$tel = trim($this->input->post('tel-f')).trim($this->input->post('tel-s')).trim($this->input->post('tel-t'));
	if($tel != ''){
	    $pattern = '/^[0][1-9]([0-9]{7,8})$/';
	    if( ! preg_match($pattern, $tel)) {
		$data['status'] = FALSE;
		$data['error'] .= 'เบอร์โทรศัพท์มือถือไม่ถูกต้องค่ะ<br />';
	    }else{
		$data['tel'] = $tel;
	    }
	}else{
	    $data['status'] = FALSE;
	    $data['error'] .= 'กรุณากรอกเบอร์โทรศัพท์มือถือค่ะ<br />';
	}
	
	echo json_encode($data);
    }
    
    function prizes()
    {
	if( ! $this->input->post('name', TRUE)){
	    redirect(site_url());
	    exit;
	}
	
	if($this->session->userdata('fb_app_id',TRUE) OR $this->session->userdata('fb_app_id') == '' ){
	    $this->set_facebook_data();
	}
	
	$data['fb_app_id'] = $this->session->userdata('fb_app_id');
	$data['fb_page_url'] = $this->session->userdata('fb_page_url');
	$data['fb_id'] = $this->session->userdata('fb_id');
	$user_id = $this->session->userdata('user_id');
	
	$data['name'] = $this->input->post('name');
	$data['tel'] = $this->input->post('tel');
	$data['credit'] = $this->input->post('credit');
	
	// ตรวจสอบว่าวันนี้มีแข่งหรือเปล่า
	$current_date = strtotime(date('d-m-Y 00:00:00'));
	$this->load->model('admin/round_model','round_model');
	$this->round_model->set_where(array('date'=>$current_date , 'status'=>'1'));
	$rounds = $this->round_model->load_records();
	if( ! is_array($rounds)){
	    $input['fb_id'] = $data['fb_id'];
	    $input['user_id'] = $user_id;
	    $input['name'] = $data['name'];
	    $input['tel'] = $data['tel'];
	    $input['card_no'] = $data['credit'];
	    $input['date_add'] = time();
	    $input['round_id'] = '-1';
	    $input['question_id'] = '-1';
	    $input['answer_id'] = '-1';
	    $input['is_win'] = '-1';
	    $input['status'] = '0';
	    $this->load->model('admin/user_answer_model','user_answer_model');
	    $user_answer_id = $this->user_answer_model->insert_record($input);
	    
	    $data['answer_order_hidden'] = 'hidden';
	    $data['answer_order'] = '';
	    $data['prizes_remain'] = '';
	    $data['sorry_img'] = 'sorry-msg-round-end.png';
	    $data['sorry_title'] = 'หมดรอบกิจกรรมของวันนี้แล้ว กลับมาร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
	    $this->mytpl->set_template('home/sorry.html');
	    $this->mytpl->set_cache(86400);
	    $this->mytpl->set_var($data);
	    $this->mytpl->display();
	    exit;
	}
	
	// ตรวจสอบว่ามีรอบหรือไม่
	$current_round_time = (date('G')+1);
	$round_time_check = FALSE;
	foreach($rounds as $val){
	    if($current_round_time == $val['time_period']){
		$round_time_check = TRUE;
		$round_time_id = $val['id'];
	    }
	}
	if( ! $round_time_check){
	    $input['fb_id'] = $data['fb_id'];
	    $input['user_id'] = $user_id;
	    $input['name'] = $data['name'];
	    $input['tel'] = $data['tel'];
	    $input['card_no'] = $data['credit'];
	    $input['date_add'] = time();
	    $input['round_id'] = '-1';
	    $input['question_id'] = '-1';
	    $input['answer_id'] = '-1';
	    $input['is_win'] = '-1';
	    $input['status'] = '0';
	    $this->load->model('admin/user_answer_model','user_answer_model');
	    $user_answer_id = $this->user_answer_model->insert_record($input);
	    
	    $data['answer_order_hidden'] = 'hidden';
	    $data['answer_order'] = '';
	    $data['prizes_remain'] = '';
	    $data['sorry_img'] = 'sorry-msg-round-end.png';
	    $data['sorry_title'] = 'หมดรอบกิจกรรมของวันนี้แล้ว กลับมาร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
	    $this->mytpl->set_template('home/sorry.html');
	    $this->mytpl->set_cache(86400);
	    $this->mytpl->set_var($data);
	    $this->mytpl->display();
	    exit;
	}
	
	$this->round_model->set_where(array('id'=>$round_time_id));
	$round_info = $this->round_model->load_records();
	
	// หาผู้ชนะรอบที่แล้ว
	$this->round_model->reset();
	$this->round_model->set_where(array('status'=>'1'));
	$this->round_model->set_where2('date =' , $round_info['0']['date']);
	$this->round_model->set_order_by(array('date'=>'asc' , 'time_period'=>'asc'));
	$rounds_info = $this->round_model->load_records();
	
	$round_before_id = 0;
	$data['round_before_date'] = time();
	foreach($rounds_info as $val){
	    if($val['id'] == $round_info['0']['id']){
		break;
	    }
	    $data['round_before_date'] = $val['date'];
	    $round_before_id = $val['id'];
	}
	
	$this->load->model('admin/user_answer_model','user_answer_model');
	$this->user_answer_model->set_where(array('round_id'=>$round_before_id, 'is_win'=>'1'));
	$data['winner'] = $this->user_answer_model->load_records();
	//var_dump($data['winner']);exit;
	// หาผู้ชนะรอบที่แล้ว
	
	$this->load->model('admin/prizes_model','prizes_model');
	$this->prizes_model->set_where(array('id'=>$round_info['0']['prize_id']));
	$prize_info = $this->prizes_model->load_records();
	
	$data['prize_id'] = $prize_info['0']['id'];
	$data['prize_logo'] = $prize_info['0']['logo'];
	$data['prize_img_detail'] = $prize_info['0']['detail_img'];
	$data['prize_remark'] = $prize_info['0']['remark'];
	
	$data['question_id'] = $round_info['0']['question_id'];
	$data['round_id'] = $round_time_id;
	$data['round_date'] = $current_date;
	$data['round_time'] = $current_round_time;
	
	$this->mytpl->set_template('home/prizes.html');
	$this->mytpl->set_cache(86400);
	$this->mytpl->set_var($data);
	$this->mytpl->display();
    }
    
    function announcement()
    {
	if($this->session->userdata('fb_app_id',TRUE) OR $this->session->userdata('fb_app_id') == '' ){
	    $this->set_facebook_data();
	}
	
	$data['fb_app_id'] = $this->session->userdata('fb_app_id');
	
	$data['name'] = $this->input->post('name');
	$data['tel'] = $this->input->post('tel');
	$data['credit'] = $this->input->post('credit');
	
	$this->mytpl->set_template('home/announcement.html');
	$this->mytpl->set_cache(86400);
	$this->mytpl->set_var($data);
	$this->mytpl->display();
    }
    
    function question()
    {
	if( ! $this->input->post('name', TRUE)){
	    redirect(site_url());
	    exit;
	}
	
	if($this->session->userdata('fb_app_id',TRUE) OR $this->session->userdata('fb_app_id') == '' ){
	    $this->set_facebook_data();
	}
	
	$data['fb_app_id'] = $this->session->userdata('fb_app_id');
	
	$data['name'] = $this->input->post('name');
	$data['tel'] = $this->input->post('tel');
	$data['credit'] = $this->input->post('credit');
	
	$data['prize_id'] = $this->input->post('prize_id');
	$data['question_id'] = $this->input->post('question_id');
	$data['round_id'] = $this->input->post('round_id');
	$data['round_date'] = $this->input->post('round_date');
	$data['round_time'] = $this->input->post('round_time');
	
	$this->load->model('admin/question_model','question_model');
	$this->question_model->set_where(array('id'=>$data['question_id']));
	$question_info = $this->question_model->load_records();
	
	$data['question_img'] = $question_info['0']['question_img'];
	$data['question_remark'] = $question_info['0']['remark'];
	$answer = json_decode($question_info['0']['answers']);
	$i = 1;
	foreach($answer as $key=>$val){
	    $data['answer'][$i]['id'] = $key;
	    $data['answer'][$i]['title'] = $val->title;
	    $data['answer'][$i]['img'] = $val->img;
	    $i++;
	}
	
	$this->mytpl->set_template('home/question.html');
	$this->mytpl->set_cache(86400);
	$this->mytpl->set_var($data);
	$this->mytpl->display();
    }
    
    function answer()
    {
	if( ! $this->input->post('name', TRUE)){
	    redirect(site_url());
	    exit;
	}
	
	if($this->session->userdata('fb_app_id',TRUE) OR $this->session->userdata('fb_app_id') == '' ){
	    $this->set_facebook_data();
	}
	
	$data['fb_app_id'] = $this->session->userdata('fb_app_id');
	$data['fb_page_url'] = $this->session->userdata('fb_page_url');
	$data['fb_id'] = $this->session->userdata('fb_id');
	$user_id = $this->session->userdata('user_id');
	
	$name = $this->input->post('name');
	$tel = $this->input->post('tel');
	$credit = $this->input->post('credit');
	$prize_id = $this->input->post('prize_id');
	$question_id = $this->input->post('question_id');
	$answer_id = $this->input->post('answer_id');
	$round_id = $this->input->post('round_id');
	$round_date = $this->input->post('round_date');
	$round_time = $this->input->post('round_time');
	
	// ตรวจสอบว่าได้ตอบคำถามของรอบนี้ไปหรือยัง
	$this->load->model('admin/user_answer_model','user_answer_model');
	$this->user_answer_model->set_where(array('round_id'=>$round_id, 'fb_id'=>$data['fb_id']));
	$check = $this->user_answer_model->load_records();
	if(is_array($check)){
	    //$this->mytpl->set_template('home/sorry.html');
	    //$this->mytpl->set_cache(86400);
	    //$this->mytpl->set_var($data);
	    //$this->mytpl->display();
	    //echo '111';
	    $data['sorry_img'] = 'sorry-msg-round-play.png';
	    $data['sorry_title'] = 'ขออภัยค่ะ คุณได้ร่วมกิจกรรมของรอบนี้แล้ว กลับมาร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
	    
	    $complete = FALSE;
	    $input['status'] = '1';
	}
	
	if( ! isset($complete)){
	    // ตรวจสอบว่าได้รับรางวันของวันนี้ไปหรือยัง
	    $this->user_answer_model->reset();
	    $this->user_answer_model->set_where(array('fb_id'=>$data['fb_id']));
	    $this->user_answer_model->set_where(array('is_win'=>'1'));
	    $this->user_answer_model->set_where2('date_add >=',$round_date);
	    $this->user_answer_model->set_where2('date_add <=',strtotime(date('d-m-Y 23:59:59',$round_date)));
	    $check = $this->user_answer_model->load_records();
	    if(is_array($check)){
		//$this->mytpl->set_template('home/sorry.html');
		//$this->mytpl->set_cache(86400);
		//$this->mytpl->set_var($data);
		//$this->mytpl->display();
		//echo '222';
		$data['sorry_img'] = 'sorry-msg-today-win.png';
		$data['sorry_title'] = 'ขออภัยค่ะ คุณได้รับของรางวัลสำหรับวันนี้แล้ว กลับมาร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
		$complete = FALSE;
		$input['status'] = '2';
	    }
	}
	
	$this->load->model('admin/prizes_model','prizes_model');
	$this->prizes_model->set_where(array('id'=>$prize_id));
	$temp = $this->prizes_model->load_records();
	$prizes_amount = $temp['0']['amount'];
	$prizes_jag = 0;
	
	$this->user_answer_model->reset();
	$this->user_answer_model->set_where(array('round_id'=>$round_id));
	$this->user_answer_model->set_where(array('is_win'=>'1'));
	$temp = $this->user_answer_model->load_records();
	if(is_array($temp)){
	    $prizes_jag = count($temp);
	}
	
	if( ! isset($complete)){
	    //ตรวจสอบว่าของรางวัลของรอบนี้ แจกครบไปหรือยัง
	    if(is_array($temp)){
		if( $prizes_jag >= $prizes_amount ){
		    $data['sorry_img'] = 'sorry-msg.png';
		    $data['sorry_title'] = 'ไม่ต้องเสียใจนะคะ... ร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
		    
		    $complete = FALSE;
		    $input['status'] = '3';
		}
	    }
	}
	
	if( ! isset($complete)){
	    // ตรวจสอบว่าตอบถูกต้องหรือไม่
	    $this->load->model('admin/question_model','question_model');
	    $this->question_model->set_where(array('id'=>$question_id));
	    $question_info = $this->question_model->load_records();
	    if($question_info['0']['correct_id'] != $answer_id){
		$complete = FALSE;
		
		$data['sorry_img'] = 'sorry-msg.png';
		$data['sorry_title'] = 'ไม่ต้องเสียใจนะคะ... ร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
	    }else{
		$complete = TRUE;
	    }
	}
	
	$this->user_answer_model->reset();
	$this->user_answer_model->set_where(array('round_id'=>$round_id));
	$temp = $this->user_answer_model->load_records();
	$data['answer_order_hidden'] = '';
	if(is_array($temp)){
	    $data['answer_order'] = count($temp) + 1;
	}else{
	    $data['answer_order'] = 1;
	}
	$data['prizes_remain'] = $prizes_amount - $prizes_jag;
	
	if($complete){
	    // บันทึกข้อมูลลงฐานข้อมูล และชนะ
	    $input['fb_id'] = $data['fb_id'];
	    $input['user_id'] = $user_id;
	    $input['name'] = $name;
	    $input['tel'] = $tel;
	    $input['card_no'] = $credit;
	    $input['date_add'] = time();
	    $input['round_id'] = $round_id;
	    $input['question_id'] = $question_id;
	    $input['answer_id'] = $answer_id;
	    $input['is_win'] = '1';
	    $this->user_answer_model->reset();
	    $user_answer_id = $this->user_answer_model->insert_record($input);
	    
	    // เช็คอีกที เผื่อมีการตอบเข้ามาเกือบพร้อมๆ กัน
	    $this->user_answer_model->reset();
	    $this->user_answer_model->set_where(array('round_id'=>$round_id));
	    $this->user_answer_model->set_where(array('is_win'=>'1'));
	    $this->user_answer_model->set_order_by(array('date_add'=>'ASC'));
	    $temp = $this->user_answer_model->load_records();
	    if(is_array($temp)){
		if( count($temp) > $prizes_amount ){ // ถ้าค่าแถวที่เพิ่มเข้าไป มีจำนวนมากกว่าของรางวัลที่จะแจก แสดงว่ามีคนตอบคำถามถูกพร้อมกัน ให้ตรวจสอบว่า user นี้ตอบก่อนหรือไม่
		    $i = 1;
		    $complete = FALSE;
		    foreach($temp as $val){ // วนลูปว่า user นี้ ตอบในเวลาที่กำหนดหรือไม่
			if($i <= $prizes_amount){ // วนถึงแค่จำนวนของรางวัลที่จะแจกได้
			    if($val['fb_id'] == $data['fb_id']){
				$complete = TRUE;
				break;
			    }
			}
			
			$i++;
		    }
		}
	    }
	    
	    $this->user_answer_model->reset();
	    $this->user_answer_model->set_where(array('round_id'=>$round_id));
	    $temp = $this->user_answer_model->load_records();
	    $data['answer_order_hidden'] = '';
	    $data['answer_order'] = count($temp);
	    $data['prizes_remain'] = $prizes_amount - $prizes_jag;
	    
	    if($complete){
		$data['prizes_remain'] -= 1;
		$this->mytpl->set_template('home/pleased.html');
		$this->mytpl->set_cache(86400);
		$this->mytpl->set_var($data);
		$this->mytpl->display();
	    }else{
		// ปรับ is_win ให้เป็น false
		$this->user_answer_model->reset();
		$this->user_answer_model->set_where(array('id'=>$user_answer_id));
		$this->user_answer_model->update_record(array('is_win'=>'0'));
		
		$data['sorry_img'] = 'sorry-msg.png';
		$data['sorry_title'] = 'ไม่ต้องเสียใจนะคะ... ร่วมกิจกรรมกับเราใหม่ได้ในโอกาสถัดไป';
		
		$this->mytpl->set_template('home/sorry.html');
		$this->mytpl->set_cache(86400);
		$this->mytpl->set_var($data);
		$this->mytpl->display();
	    }
	}else{
	    // บันทึกข้อมูลลงฐานข้อมูล และไม่ชนะ
	    $input['fb_id'] = $data['fb_id'];
	    $input['user_id'] = $user_id;
	    $input['name'] = $name;
	    $input['tel'] = $tel;
	    $input['card_no'] = $credit;
	    $input['date_add'] = time();
	    $input['round_id'] = $round_id;
	    $input['question_id'] = $question_id;
	    $input['answer_id'] = $answer_id;
	    $input['is_win'] = '0';
	    $this->user_answer_model->reset();
	    $user_answer_id = $this->user_answer_model->insert_record($input);
	    
	    $this->mytpl->set_template('home/sorry.html');
	    $this->mytpl->set_cache(86400);
	    $this->mytpl->set_var($data);
	    $this->mytpl->display();
	}
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */